"""
FileName：search_page.py
Description：
Author：gaojiahui
Time：2025/8/29 18:37
Website：https://gitee.com/gao-jiahui
"""
from selenium.webdriver.common.by import By

from pages.base_page import BasePage


class SearchPage(BasePage):
    # 元素定位器
    SEARCH_RESULT = (By.CSS_SELECTOR, "div.gl-item")
    PRODUCT_NAME = (By.CSS_SELECTOR, "div.gl-name")
    NO_RESULTS_MESSAGE = (By.CSS_SELECTOR, "div.empty-goods")

    def get_search_results_count(self):
        """获取搜索结果数量"""
        return len(self.find_elements(self.SEARCH_RESULT))

    def get_product_names(self):
        """获取所有搜索结果商品名称"""
        product_names = []
        for product in self.find_elements(self.PRODUCT_NAME):
            product_names.append(product.text)
        return product_names

    def select_product_by_name(self, product_name):
        """根据商品名称选择商品"""
        # 检查搜索结果是否为空
        if self.is_element_present(self.NO_RESULTS_MESSAGE):
            raise Exception("No products found in search results")
        # 检查商品名称是否存在
        product_locator = (By.XPATH, f"//div[@class='gl-name']/a[@title='{product_name}']")
        if self.is_element_present(product_locator):
            product = self.find_element(product_locator)
            product.click()
            from pages.product_page import ProductPage
            return ProductPage(self.driver)
        else:
            raise Exception(f"Product {product_name} not found in search results")

    def get_no_results_message(self):
        """获取没有搜索结果的提示信息"""
        return self.get_text(self.NO_RESULTS_MESSAGE)
